package org.zhangsh.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
import org.zhangsh.socket.HostInfo;

import java.nio.charset.StandardCharsets;

/**
 * </p>
 *
 * @author zhangsh
 * @version 1.0.0
 * @since 2019-04-27
 */
public class TimerClientHandler extends ChannelInboundHandlerAdapter {

    private ByteBuf firstMessage = null;
    private byte[] request = null;
    private int counter;

    public TimerClientHandler(){
        request = (HostInfo.QUERY_TIME + HostInfo.SEPARATOR).getBytes();
        firstMessage = Unpooled.buffer(request.length);
        firstMessage.writeBytes(request);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(HostInfo.THREAD_NAME + "向服务端请求数据...");

        StringBuilder data = new StringBuilder();

        /*for (int i = 0; i < 1025; i++) {
            data.append("A");
        }*/
//        data.append("hello\0");

//        ctx.writeAndFlush(data.toString());
//        ctx.writeAndFlush("hello\0");
        Thread.sleep(3000);

        ctx.writeAndFlush("hello\0");
        Thread.sleep(3000);

        ctx.writeAndFlush("hello\0");
        Thread.sleep(3000);

        ctx.writeAndFlush("hello\0");
        Thread.sleep(3000);

//        Thread.sleep(6000);

//        ctx.writeAndFlush(" world"+"\0");

        System.out.println("发送完毕");
        /*ByteBuf byteBuf = null;
        for(int i=0; i<10; i++){
            byteBuf = Unpooled.buffer(request.length);
            byteBuf.writeBytes(request);
            ctx.writeAndFlush(byteBuf);
        }*/
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        System.out.println(HostInfo.THREAD_NAME + "开始读");

        /*ByteBuf reponse = (ByteBuf) msg;
        byte[] reciver = new byte[reponse.readableBytes()];
        reponse.readBytes(reciver);
        String body = new String(reciver, StandardCharsets.UTF_8);*/
        String body = (String) msg;

        System.out.println(HostInfo.THREAD_NAME + "接收数据：" + body + " ; the counter " + ++counter);

//        super.channelRead(ctx, msg);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        System.out.println(HostInfo.THREAD_NAME + "读完成");
        super.channelReadComplete(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println(HostInfo.THREAD_NAME + "异常");
        ctx.close();
    }
}
